<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <a-card :bordered="false">
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.id"
          :rowSelection="null"
          bordered
        >
          <span slot="action" slot-scope="text, record">
            <a
              :href="pdfUrl"
              @click="previewPdf(record)"
              target="_blank"
            >
              <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
                <a-icon type="eye" />
                预览
              </a-button>
            </a>
            <div class="pdf-overlay" @click="closePreview" v-if="pdfData">
              <progress v-if="loadingProgress" :value="loadingProgress" max="100"></progress>
            </div>
            <embed
              v-if="pdfData"
              :src="pdfData"
              type="application/pdf"
              width="100%"
              height="100%"
              class="pdf-container" />
            <a @click="handleExport(record)" :loading="batchExportLoading">
              <a-button size="small" style="color: #403463;background: #e6e6fd;border-color: #b29af9; margin-left: 5px;">
                <a-icon type="download" />
                下载
              </a-button>
            </a>
          </span>
        </s-table>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
  import { STable, XCard, XDown } from '@/components'
  import {
    getQHSEManStandard,
    getDownloadPdf,
    getPreviewPdf
  } from '@/api/modular/system/QHSEManager'
  export default {
    components: {
      XDown,
      XCard,
      STable
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        // 表头
        columns: [
          {
            title: '序号',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '文档分类',
            dataIndex: 'standardCode'
          },
          {
            title: '文档名称',
            dataIndex: 'fileName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        fileName: '',
        queryParam: {
          code: '',
          name: ''
        },
        exportParam: {
          id: ''
        },
        param: {
          id: '',
          name: ''
        },
        batchExportLoading: false,
        filteredData: [],
        newData: [],
        pdfUrl: '',
        pdfData: '',
        loadingProgress: 0
      }
    },
    created() {
      this.loadData()
    },
    methods: {
        loadData() {
        return getQHSEManStandard(Object.assign(this.queryParam)).then((res) => {
          console.log('表格数据', res.data)
          // 筛选出"standardCode"为"管理制度"的数据
          this.filteredData = res.data.rows.filter(item => item.standardCode === '管理制度')
          var count = 0
          var Page = 1
          if (this.filteredData === '管理制度') {
            count++
            if (count > 10) {
              Page++
            }
          }
          // 构造新的返回对象，保持返回格式和原来的 res.data 一致
          this.newData = {
            ...res.data,
            rows: this.filteredData,
            totalRows: count,
            totalPage: Page
          }
          // console.log(this.newData)
          return this.newData
        })
      },
      closePreview() {
        this.pdfData = '' // 清空 pdfData，隐藏预览内容
      },
      // handlePreview(record) {
      //   const base64Content = record.file.base64Content
      //   const contentType = 'application/pdf'// 假设是 PDF 文件类型

      //   if (typeof base64Content === 'string') {
      //     const byteCharacters = atob(base64Content)
      //     const byteNumbers = new Array(byteCharacters.length)
      //     for (let i = 0; i < byteCharacters.length; i++) {
      //       byteNumbers[i] = byteCharacters.charCodeAt(i)
      //     }
      //     const byteArray = new Uint8Array(byteNumbers)
      //     const blob = new Blob([byteArray], { type: contentType })

      //     const reader = new FileReader()
      //     reader.onprogress = (event) => {
      //       if (event.lengthComputable) {
      //         const percentLoaded = (event.loaded / event.total) * 100
      //         this.loadingProgress = percentLoaded
      //       }
      //     }
      //     reader.onload = () => {
      //       this.pdfData = reader.result
      //     }
      //     reader.readAsDataURL(blob)
      //   } else {
      //     console.error('Invalid base64 content.')
      //   }
      // },
      hideProgress() {
        this.loadingProgress = 0
      },
      previewPdf(record) { // 在此执行预览操作
        this.param.id = record.id
        this.param.name = record.fileName
        this.pdfUrl = null // 在预览之前先清空pdfUrl
        getPreviewPdf(Object.assign({}, this.param)) // 注意需要传递副本，以避免影响其他地方的param
          .then(response => {
            // 使用 Blob 构造函数创建一个 PDF 文件的对象 URL
            const fileBlob = new Blob([response.data], { type: 'application/pdf' })
            this.pdfUrl = URL.createObjectURL(fileBlob)
            if (this.pdfUrl) {
              // Open the PDF in a new tab
              window.open(this.pdfUrl, '_blank')
            }
          })
          .catch(error => {
            console.error('预览失败:', error)
          })
      },
      handleExport(record) { // 在此执行下载操作
          this.param.id = record.id
          this.param.name = record.fileName
          // console.log(this.param.name)
          this.getDownloadPdf()
     },
     getDownloadPdf() {
      getDownloadPdf(Object.assign(this.param)).then(response => {
          // 从response的headers中获取content-disposition字段，该字段包含服务器返回的文件名
          this.filename = this.param.name
          // 创建下载链接
          const downloadLink = document.createElement('a')
          downloadLink.href = window.URL.createObjectURL(response.data)
          // 设置下载链接的属性
          downloadLink.download = this.filename + '.pdf'
          downloadLink.target = '_blank'
          // 在下载链接的 click 事件处理程序中停止加载状态
          downloadLink.addEventListener('click', () => {
            this.batchExportLoading = false
          })
         // 触发下载
         try {
          downloadLink.click()
         } catch (error) {
              console.error('下载失败:', error)
              this.batchExportLoading = false
            }
          })
      }
    }
  }
</script>

<style scoped>
 .ant-table-tbody tr:nth-child(2n) {
    background-color:#FAFAFA;
  }
.pdf-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  justify-content: center;
  align-items: center;
  background-color: #3d6ed8;
}
</style>
